import axios, { type AxiosResponse, type AxiosRequestHeaders } from 'axios'
import { showSuccessToast, showFailToast } from 'vant';
import useUserStore from '@/stores/user';
import { anyObjModel } from '@/api/category';
interface RequestModel<T> {
  code?: string | number
  data: T
  message?: string
}

const request = axios.create({
  // baseURL: '/api',
  timeout: 20000
})

request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    const token = userStore.token
    
    if(token){
      config.headers.token = token
    }else {
      config.headers.token = "fb961927ac33db422087839e2ceb5012"
    }
    return config
  }
)

request.interceptors.response.use(
  async (response: AxiosResponse<RequestModel<any>,any>) => {
    const res = response.data;
    
    if(res.code){
      if(res.message && !res.data){
        return res
      }
      if(res.code !== "20000" && res.code !== "200" && res.code !== 200 && res.code !== 20000){
        showFailToast((typeof res.data=='string' && res.data)|| res.message || 'Error');
        return Promise.reject('请求有误')
      }else {
        return res.data
      }
    }else {
      return res
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf('timeout') != -1) {
      showFailToast('网络超时');
    } else if (error.message == 'Network Error') {
      showFailToast('网络连接错误');
    } else {
      if (error.response.data) showFailToast(error.response.statusText);
      else showFailToast('接口路径找不到');
    }
    return Promise.reject(error);
  }
)


export default request
 